package com.taotao.sso.service;

import java.io.IOException;
import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.taotao.common.service.RedisService;
import com.taotao.sso.mapper.UserMapper;
import com.taotao.sso.pojo.User;

@Service
public class UserService {
	
	@Autowired
	private RedisService redisService;
	
	@Autowired
	private UserMapper userMapper;
	
	private static final String TT_TOKEN_PREFIX = "TT_TOKEN_";

	/**
	 * 验证用户名 邮箱 电话是否可用
	 * @param param
	 * @param type
	 * @return
	 */
	public Boolean checkUser(String param, Integer type) {
		
		User record = new User();
		switch (type) {
		case 1:
			record.setUsername(param);
			break;
		case 2:
			record.setPhone(param);
			break;
		case 3:
			record.setEmail(param);
			break;

		default:
			return null;
		}
		// 如果查询的结果为0，说明该用户名 电话 邮箱没有被占用
		return this.userMapper.selectCount(record) == 0;
		
	}

	/**
	 * 用户注册方法
	 * @param user
	 * @return
	 */
	public Boolean register(User user) {
		// 对密码MD5加密
		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		// 初始化创建时间和更新时间
		user.setCreated(new Date());
		user.setUpdated(user.getCreated());
		return this.userMapper.insert(user) == 1;
	}

	/**
	 * 实现登陆逻辑
	 * @param userName
	 * @param password
	 * @return
	 * @throws JsonProcessingException
	 */
	public String login(String userName, String password) throws JsonProcessingException {
		// 查询用户存不存在
		User record = new User();
		record.setUsername(userName);
		User user = this.userMapper.selectOne(record);
		// 判断用户
		if(user == null){
			
			return null;
		}
		
		// 判断密码是否一致
		if(!StringUtils.equals(user.getPassword(), DigestUtils.md5Hex(password))){
			
			return null;
		}
		
		// 登陆成功
		String token = DigestUtils.md5Hex(user.getUsername() + System.currentTimeMillis());
		this.redisService.set(TT_TOKEN_PREFIX + token, user, 3600*3l);
		
		return token;
	}

	/**
	 * 根据token查询登陆状态
	 * @param token
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public User queryUserByToken(String token) throws JsonParseException, JsonMappingException, IOException {
		// 查询登陆状态
		User user = this.redisService.get(TT_TOKEN_PREFIX + token, new TypeReference<User>() {
		});
		// 如果redis中没有，退出登陆状态
		if(user == null){
			return null;
		}
		// 如果redis中有，是登陆状态，重新刷新生存时间
		this.redisService.expire(TT_TOKEN_PREFIX + token, 3600*3l);
		
		return user;
	}

}
